<template>
  <div class="app-container">
    <el-input style="width: 250px;" v-model="queryParams.goodsName" placeholder="商品名称"></el-input>
    <el-dropdown style="margin-left: 20px; width: 120px;">
      <el-select v-model="queryParams.languageCode" placeholder="语言分类">
      <el-option
        v-for="item in languageList"
        :key="item.code"
        :label="item.languageName"
        :value="item.code">
      </el-option>
      </el-select>
    </el-dropdown>
    <el-dropdown style="margin-left: 20px; width: 120px;">
      <el-select v-model="queryParams.status" placeholder="商品状态">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value">
      </el-option>
      </el-select>
    </el-dropdown>

    <el-date-picker
      style="margin-left: 20px;"
      v-model="dateRange"
      type="daterange"
      range-separator="至"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      @change="handleDateChange"
      value-format="yyyy-MM-dd">
    </el-date-picker>

    <el-button style="margin-left: 20px;" @click="handleQuery" type="primary" icon="el-icon-search">搜索</el-button>
    <el-button style="margin-left: 20px;" @click="handleReset" type="info" icon="el-icon-refresh-left">重置</el-button>
    <el-button style="margin-left: 20px;" @click="handleExport" type="success"  icon="el-icon-bottom">导出</el-button>
    <br></br>
    <el-button  @click="openDialog" type="warning" round icon="el-icon-circle-plus-outline">新增</el-button>
    
    
    <!-- 对话框 -->
    <el-dialog :title="isEditMode ? '编辑商品' : '添加商品'"   
               :visible.sync="dialogVisible"
               @close="handleAddCancel" 
               width="50%">
      <!-- 表单 -->
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="110px">
        <el-form-item label="销售语言：" prop="languageCode">
          <template>
            <el-select v-model="formData.languageCode" placeholder="请选择">
              <el-option
                v-for="item in languageList"
                :key="item.code"
                :label="item.languageName"
                :value="item.code">
              </el-option>
            </el-select>
          </template>
        </el-form-item>

        <el-form-item label="商品名称：" prop="goodsName">
          <el-input v-model="formData.goodsName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="商品主标题：" prop="title">
          <el-input v-model="formData.title" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="商品副标题：" prop="subtitle">
          <el-input v-model="formData.subtitle" placeholder="请输入"></el-input>
        </el-form-item>

        <el-form-item label="主图：" prop="imageList">
          <el-upload
            class="upload-demo"
            action="https://panel.lantotech.com/blade/goods/uploadImg"
            :headers="uploadHeaders"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-fail="handleError"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            :limit="3"
            list-type="picture-card">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip" style="display: inline-block; margin-left: 15px;vertical-align: middle;">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品内容：" prop="content">
          <template>
            <div>
              <quill-editor
                ref="quillEditor"
                v-model="formData.content"
                :options="editorOption"
                style="height: 200px;"
              />
            </div>
          </template>
        </el-form-item>
        <el-form-item label="购买地址：" style="margin-top: 80px;" prop="link">
          <el-input v-model="formData.link" placeholder="请输入"></el-input>
        </el-form-item>
        
      </el-form>
      
      <!-- 对话框底部按钮 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAddCancel">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
    <br></br>
    <el-table
      v-loading="listLoading"
      :data="goodsList"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="商品ID" width="170">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="商品名称">
        <template slot-scope="scope">
          {{ scope.row.goodsName }}
        </template>
      </el-table-column>
      <el-table-column label="商品主图" width="600" align="center">
        <template slot-scope="scope">
          <div class="image-preview"> 
            <el-image 
            v-for="(img, index) in scope.row.imageList"
            style="width: 130px; height: 110px" 
            :src="img"
            :key="index"
            fit="cover"
            class="thumbnail"
            >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="语言分类" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.languageName }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" prop="created_at" label="新建时间" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="状态" width="110" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusStyleFilter">{{ scope.row.status | statusTextFilter }}</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column align="center" label="操作" width="250">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)" :disabled="scope.row.status === 1 ">编辑</el-button>
          <el-popover placement="top" width="160" v-model="scope.row.visible1">
            <p>
              {{ getStatusText(scope.row.status) }}
            </p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="scope.row.visible1 = false">取消</el-button>
              <el-button type="primary" size="mini" @click="changeStatus(scope.row)">确定</el-button>
            </div>
            <el-button :type="scope.row.status | buttonStyleFilter" size="small" slot="reference" style="margin-left: 10px;">
              {{ scope.row.status | buttonFilter }}
            </el-button>
            
          </el-popover>
          
          <el-popover placement="top" width="160" v-model="scope.row.visible2">
            <p>确定删除这一商品？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="scope.row.visible2 = false">取消</el-button>
              <el-button type="primary" size="mini" @click="handleDelete(scope.row)">确定</el-button>
            </div>
            <el-button type="danger" size="small" slot="reference" style="margin-left: 10px;">删除</el-button>
          </el-popover>
        </template>
      </el-table-column>
      
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="pagination-container"
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="queryParams.pageNo"
      :page-sizes="[10, 20, 50, 100]"
      :page-size= queryParams.pageSize
      layout="total,sizes,prev, pager, next"
      :total=total
    />
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { getList } from '@/api/language'
import { query,submitFormData,changeStatus,deleteGoods,uploadImg,updateGoods,exportExcel } from '@/api/goods'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {

  components: { quillEditor },
  filters: {
    statusStyleFilter(status) {
      const statusMap = {
        '1': 'success',
        '-1': 'info'
      }
      return statusMap[status] || 'danger'
    },
    statusTextFilter(status) {
      const map = {
        '1': '已上架',
        '-1': '已下架',
        '0': '待上架'
      }
      return map[status] || '未知状态'
    },
    buttonFilter(status) {
      const map = {
        '1': '下架',
        '0': '上架',
        '-1': '上架'
      }
      return map[status] || '-'
    },
    buttonStyleFilter(status) {
      const map = {
        '1': 'info',
        '-1': 'warning',
        '0': 'warning'
      }
      return map[status] || '-'
    }
  },
  data() {
    return {
      submitLoading: false,
      isEditMode: false, 
      currentEditId: null, 
      editImageList: [], 
      total:0,
      fileList: [],
      // 上传接口的token
      uploadHeaders:{'Authorization': `Bearer ${this.getTokenMethod()}`},
      visible1: false,
      visible2: false,
      options: [{
          value: 1,
          label: '已上架'
        }, 
        {
          value: 0,
          label: '待上架'
        },
        {
          value: -1,
          label: '已下架'
        }],
      value: '',
      goodsList:[],
      listLoading: true,
      pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      startTime:'',
      endTime:'',
      dialogVisible: false, // 控制对话框显示
      formData: {
        languageCode:'',
        title:'',
        subtitle:'',          
        goodsName: '',
        imageList:[],
        content: '',
        link: '',
        status:1
      },
      languageList:[],
      //查询参数
      queryParams: {
        goodsName: '',
        languageCode:'',
        status:'',
        startDate: '',
        endDate: '',
        pageNo: 1,
        pageSize: 10
      },
      dateRange: [],
      editorOption: {
        placeholder: '请输入文字/图片',
        theme: 'snow',  
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'],
              ['blockquote', 'code-block'],
              [{ 'header': 1 }, { 'header': 2 }],
              [{ 'list': 'ordered'}, { 'list': 'bullet' }],
              [{ 'indent': '-1'}, { 'indent': '+1' }],
              [{ 'size': ['small', false, 'large', 'huge'] }],
              [{ 'color': [] }, { 'background': [] }],
              [{ 'align': [] }],
              ['image','link'],
            ],
            handlers: {
              image: this.handleImageUpload  // 图片上传处理器
            }
          }
        }
      },
      formRules: {          
        languageCode: [
          { required: true, message: '请选择销售语言', trigger: 'change' }
        ],
        goodsName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度不能超过50', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入主标题', trigger: 'blur' },
          { min: 1, max: 100, message: '长度不能超过50', trigger: 'blur' }
        ],
        subtitle:[
          { min: 0, max: 100, message: '长度不能超过50', trigger: 'blur' }
        ],
        imageList:[
          { required: true, message: '请上传商品主图', trigger: 'change' }
        ],
        content:[
          { required: true, message: '请输入商品详情', trigger: 'blur' }
        ],
        link:[
          { required: true, message: '请输入商品链接', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.listLoading = true
    this.listLoading = false
    this.handleQuery()
    this.getLanguageList()
  },
  methods: {
    getStatusText(status) {
      const statusMap = {
        '-1': '确定上架？',
        '0':  '确定上架？',
        '1': '确定下架？'
      }
      return statusMap[status] || '未知状态'
    },
    // Quill图片上传处理
    handleImageUpload() {
      
      const input = document.createElement('input')
      input.setAttribute('type', 'file')
      input.setAttribute('accept', 'image/*')
      input.click()
    
      input.onchange = async () => {
        const file = input.files[0]
        if (!file) return
        
        // 显示上传loading
        const loading = this.$loading({
          lock: true,
          text: '图片上传中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        
        try {
          // 上传到MinIO
          const formData = new FormData()
          formData.append('file', file)
          
          const res = await uploadImg(formData)
          const url = res.data.url
          console.log(url)
          // 获取编辑器当前光标位置
          const quill = this.$refs.quillEditor.quill
          console.log('1')
          const range = quill.getSelection()
          console.log('3')
          // 插入图片到编辑器
          quill.insertEmbed(range.index, 'image', url)
          quill.setSelection(range.index + 1)
          console.log('4')
        } catch (error) {
          this.$message.error('图片上传失败')
        } finally {
          loading.close()
        }
      }
    },
    // 处理日期范围变化
    handleDateChange(val) {
      if (val && val.length === 2) {
        this.queryParams.startDate = val[0]
        this.queryParams.endDate = val[1]
      } else {
        this.queryParams.startDate = ''
        this.queryParams.endDate = ''
      }
    },
    handleEdit(row) {
      this.isEditMode = true
      this.currentEditId = row.id
      this.dialogVisible = true
      
      // 深拷贝商品数据到表单
      this.formData = {
        id: row.id,
        languageCode: row.languageCode,
        goodsName: row.goodsName,
        title: row.title,
        subtitle: row.subtitle,
        content: row.content,
        link: row.link,
        status: row.status,
        imageList: [...row.imageList]
      }
  
      // 初始化图片上传组件显示
      this.fileList = row.imageList.map((url, index) => ({
        uid: index,
        name: `image_${index}.jpg`,
        url: url,
        status: 'success'
      }))
     },
    getTokenMethod() {
      return getToken() || ''
    },
    handleDelete(row){
      row.visible2 = false
      deleteGoods(row.id).then(response => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        
        this.handleQuery()
      })
    },
    submitForm() {
      this.$refs.formRef.validate(valid => {
      if (valid) {
        this.submitLoading = true;
        const apiMethod = this.isEditMode 
          ? updateGoods(this.formData) 
          : submitFormData(this.formData)
        
        apiMethod.then(response => {
          if (response.code === 200) {
              this.$message({
                message: this.isEditMode ? '修改成功' : '新增成功',
                type: 'success'
            })
          }
          this.dialogVisible = false
          this.handleQuery()
          this.handleAddCancel()
        })
        this.submitLoading = false;
      }
    })
    },
    // 查询
    handleQuery(){
      const params = {
        goodsName: this.queryParams.goodsName,
        languageCode: this.queryParams.languageCode,
        status: this.queryParams.status,
        startDate: this.queryParams.startDate,
        endDate: this.queryParams.endDate,
        pageNo: this.queryParams.pageNo,
        pageSize: this.queryParams.pageSize
      }
      query(params).then(response => {
        //console.log(response);
        this.goodsList = response.data.records
        this.total = response.data.total
      })
    },
    getLanguageList(){
      getList().then(response => {
        this.languageList = response.data
      })
    },
    // 条件重置
    handleReset(){
      this.queryParams = {
        goodsName: '',
        languageCode:'',
        status: '',
        startDate: '',
        endDate: '',
        pageNo: 1,
        pageSize: this.queryParams.pageSize
      }
      this.dateRange = [] // 同时清空日期选择器
      this.handleQuery()
    },
    // 导出数据
    handleExport() {
      const params = {
        goodsName: this.queryParams.goodsName,
        languageCode: this.queryParams.languageCode,
        status: this.queryParams.status,
        startDate: this.queryParams.startDate,
        endDate: this.queryParams.endDate,
        pageNo: this.queryParams.pageNo,
        pageSize: this.queryParams.pageSize
      }
      exportExcel(params).then(response => {
        const blob = new Blob([response.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        })
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = '商品列表.xlsx'
        link.click()
        URL.revokeObjectURL(link.href)
      }).catch(error => {
        this.$message.error('导出失败')
        console.error(error)
      })
    },
    // 取消新增
    handleAddCancel() {
      this.fileList = []
      this.formData = {
        languageCode: '',
        title: '',
        subtitle: '',          
        goodsName: '',
        imageList: [],
        content: '',
        link: '',
        status: 1
      }
      this.isEditMode = false
      this.currentEditId = null
      this.dialogVisible = false
      this.$nextTick(() => {
        this.$refs.formRef.resetFields();  // 重置字段值和校验状态
        this.$refs.formRef.clearValidate(); // 清除校验提示（双保险）
      });
    },
    openDialog(){
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef?.resetFields(); // 确保DOM更新后重置
        this.formData = {
          languageCode: '',
          title: '',
          subtitle: '',          
          goodsName: '',
          imageList: [],
          content: '',
          link: '',
          status: 1
        }
      });
  },
    fetchData() {
      this.listLoading = true
      getList().then(response => {
        this.list = response.data.items
        this.listLoading = false
      })
    },
    handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.queryParams.pageSize = val
        this.handleQuery()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.queryParams.pageNo = val
      this.handleQuery()
    },
    // 上下架
    changeStatus(row) {
      row.visible1 = false
      // api调用
      try { 
        changeStatus(row.id, row.status).then(res => { 
          // 切换状态
          if (row.status === 1) {
            row.status = -1
            this.$message.success('已下架')
          } else {
            row.status = 1
            this.$message.success('已上架')
          }
          this.handleQuery()
        });
        
      } catch (error) {
        console.error(error);
        if (error.message !== '登录已过期') {
          this.$message.error('操作失败: ' + error.message)
        }
      }
    
    },
    // 图片
    handleRemove(file, fileList) {
        // 从formData.imageList中移除对应的图片URL
      this.formData.imageList = this.formData.imageList.filter(
        url => url !== file.url
      )
      this.fileList = fileList
    },
    handleExceed() {
      this.$message.warning(`最多只能上传 3 张图片`);
    },
    // handlePreview(file) {
    //   console.log(file);
    //   // 可以在这里实现图片预览功能
    //   window.open(file.url);
    // },
    handleSuccess(response, file, fileList) {
      this.formData.imageList.push(response.data.url)
      this.$message.success('上传成功')
    },
    handleError(err, file, fileList) {
      console.error('上传失败', err, file, fileList);
      this.$message.error('上传失败');
    },
    handleUpload(file) {
    // 创建本地URL用于预览
    const url = URL.createObjectURL(file.file);
    console.log("有上传操作")
    uploadImg(file).then(response => {
      console.log(response);
    })
    this.fileList.push({
      name: file.file.name,
      url: url
    });
    return true; 
  },
  beforeUpload(file) {
    const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isImage) {
      this.$message.error('仅支持 JPG/PNG 格式!');
    }
    if (!isLt2M) {
      this.$message.error('上传头像图片大小不能超过 2MB!');
    }
    return isImage && isLt2M;
  },
  
  }
}
</script>


<style scoped>
  .pagination-container {
    display: flex;
    justify-content: flex-end; 
    margin-top: 20px;
    margin-right: 30px;
  }
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: #f5f5f5;
    color: #909399;
    font-size: 30px;
  }
  .text-ellipsis {
    display: inline-block;
    width: 200px; /* 或根据实际需要设置 */
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .thumbnail {
    width: 60px;
    height: 50px;
    margin-right: 8px;
    border-radius: 4px;
  }
</style>